package com.xrtn.service.impl;

import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.service.ICommonService;
import com.xrtn.service.IDoctorService;
import com.xrtn.utils.*;
import io.netty.util.internal.ObjectUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * Created by tu_pei on 2018/2/27.
 */
@Service
public class DoctorServiceImpl implements IDoctorService {
    /**
     * 大夫表
     */
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    /**
     * 用户表
     */
    @Autowired
    private TUserInfoMapper userInfoMapper;

    @Autowired
    private TPatientInfoMapper patientInfoMapper;

    /**
     * 大夫等级规则表
     */
    @Autowired
    private InitGradeDoctorMapper gradeDoctorMapper;

    /**
     * 分店表
     */
    @Autowired
    private TSubclinicInfoMapper subclinicInfoMapper;
    /**
     * 预约信息表
     */
    @Autowired
    private TBookingInfoMapper bookingInfoMapper;
    /**
     * 基础调查信息表
     */
    @Autowired
    private TPatientInitMapper patientInitMapper;
    /**
     * 病史档案信息表
     */
    @Autowired
    private TPatientHistoryMapper patientHistoryMapper;

    /**
     * 患者病历信息
     */
    @Autowired
    private TPatientTreatmentMapper patientTreatmentMapper;
    /**
     * 穴位信息表
     */
    @Autowired
    private TUserPointRelMapper userPointRelMapper;
    /**
     * 病症信息表
     */
    @Autowired
    private TUserDiseaseRelMapper userDiseaseRelMapper;
    /**
     * 订单信息表
     */
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    /**
     * 订单商品明细表
     */
    @Autowired
    private TOrderGoodsDetailMapper orderGoodsDetailMapper;
    /**
     * 订单推拿服务表
     */
    @Autowired
    private TOrderServiceDetailMapper orderServiceDetailMapper;
    /**
     * 请假信息表
     */
    @Autowired
    private TOffInfoMapper offInfoMapper;
    /**
     * APP版本信息表
     */
    @Autowired
    private SysVersionInfoMapper versionInfoMapper;

    @Autowired
    private TUserConclusionRelMapper conclusionRelMapper;

    @Autowired
    private TDoctorPushRelMapper doctorPushRelMapper;

    @Autowired
    private TUserTreatmentRelMapper userTreatmentRelMapper;

    @Autowired
    private InitRecordAnswerMapper initRecordAnswerMapper;

    @Autowired
    private AccountUserInfoMapper accountUserInfoMapper;

    @Autowired
    private AccountDoctorInfoMapper accountDoctorInfoMapper;

    /**
     * 登录
     *
     * @param account
     * @param userPwd
     * @return
     */

    @Override
    public Map<String, Object> sign(String account, String userPwd) {

        Map<String, Object> params = new HashMap<>();
        params.put("userNo", account);
        params.put("userStatus", 0);
        SysUserInfo sysUserInfo = sysUserInfoMapper.selectByUserInfo(params);

        if (ObjUtils.isNotEmpty(sysUserInfo)) {
            //如果密码不为空
            if (ObjUtils.isNotEmpty(sysUserInfo.getUserPwd())) {
                // 如果密码匹配成功
//                System.out.println("userPwd=" + MD5Utils.md5Password(userPwd));
                if (MD5Utils.md5Password(userPwd).equals(sysUserInfo.getUserPwd())) {
                    // 返回这个对象
                    params.put("userInfo", sysUserInfo);
                    return params;
                } else {
                    // 否则说明密码错误
                    params.put("EnumCode", CodeEnum.CODE_10002);
                    return params;
                }
            } else {
                //否则需要进行注册
                params.put("EnumCode", CodeEnum.CODE_10007);
                return params;
            }
        } else {
            // 那么用户不存在
            params.put("EnumCode", CodeEnum.CODE_10003);
            return params;
        }
    }

    /**
     * 获取首页信息
     *
     * @param userId
     * @param bookingDate
     * @return
     */
    @Override
    public Map<String, Object> desktop(Integer userId, String bookingDate) {

        Map<String, Object> retMap = new HashMap<>();

        SysUserInfo userInfo = sysUserInfoMapper.selectByPrimaryKey(userId);

        TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectByPrimaryKey(userInfo.getSubclinicId());

        List<TBookingInfo> bookingList = bookingInfoMapper.selectBookingListByDoctorId(userId, bookingDate);

        retMap.put("userInfo", userInfo);
        retMap.put("subclinicInfo", subclinicInfo);
        retMap.put("bookingList", bookingList);

        return retMap;
    }

    /**
     * 获取最新版本
     *
     * @param versionInfo
     * @return
     */
    @Override
    public SysVersionInfo existNewVersion(SysVersionInfo versionInfo) {

        Map<String, Object> params = new HashMap<>();
        params.put("equipmentType", versionInfo.getEquipmentType());

        SysVersionInfo version = versionInfoMapper.selectByMap(params);

        if (ObjUtils.isEmpty(version)) {
            return null;
        }

        if (version.getVersionCode() > versionInfo.getVersionCode()) {
            return version;
        }

        return null;
    }

    /**
     * 根据患者id查询患者诊疗进度
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> selectTherapySchedule(Integer userId, Integer bookingId) {

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", userId);
        params.put("bookingId", bookingId);
        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(bookingId);

        TPatientTreatment patientTreatment = patientTreatmentMapper.selectByMap(params);
        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);
        params.put("bookingId", null);

        List<TDoctorPushRel> pushList = doctorPushRelMapper.selectByMap(params);
        Map<String, Object> patientInit = patientInitMapper.selectByMap(params);
        TPatientHistory patientHistory = patientHistoryMapper.selectByPatientId(userId);
        params = new HashMap<>();

        if(bookingInfo.getBookingType() == 0){
            // 技师端 患者就诊阶段 ： 1，2，3，4，5，6
            if (ObjUtils.isNotEmpty(patientInit)) {
                if (ObjUtils.isNotEmpty(patientHistory) && ObjUtils.isNotEmpty(patientHistory.getAllergyHistory())
                        && ObjUtils.isNotEmpty(patientHistory.getUserHistory()) && ObjUtils.isNotEmpty(patientHistory.getMedicineHistory())
                        && ObjUtils.isNotEmpty(patientHistory.getFeverHistory())) {
                    //已存在患者
                    Object bookingObjId =  patientInit.get("bookingId");
                    Integer bookingIds = 0;
                    if(ObjUtils.isNotEmpty(bookingObjId)){
                        bookingIds = Integer.parseInt(bookingObjId.toString());
                    }
                    if (bookingIds == bookingId) {
                        params.put("status", patientInit.get("therapyStatus"));
                        //基础调查更新时间
                        params.put("initUpdateTime", patientInit.get("createTime"));
                        if (ObjUtils.isNotEmpty(orderInfo)) {
                            //考虑待支付情况下状态变化
                            if (pushList.size() > 0) {
                                params.put("status", 5);
                                if (orderInfo.getOrderState() == 0) {
                                    params.put("status", 6);
                                }
                            }
                        }
                    } else {
                        if (ObjUtils.isNotEmpty(patientTreatment) && ObjUtils.isNotEmpty(patientTreatment.getTreatmentImg())
                                && ObjUtils.isNotEmpty(patientTreatment.getHandsImg()) && ObjUtils.isNotEmpty(patientTreatment.getFaceImg())
                                && ObjUtils.isNotEmpty(patientTreatment.getDiseaseInfo())) {
                            params.put("status", 3);
                            if (ObjUtils.isNotEmpty(orderInfo)) {
                                params.put("status", 4);
                                if (pushList.size() > 0) {
                                    params.put("status", 5);
                                    if (orderInfo.getOrderState() == 0) {
                                        params.put("status", 6);
                                    }
                                }
                            }
                        } else {
                            params.put("status", 2);
                        }

                        //基础调查更新时间
                    }
                } else {
                    params.put("status", 1);
                }
                params.put("initUpdateTime", patientInit.get("createTime"));
            } else {
                //新患者需要填写病史

                params.put("status", 1);
                //基础调查更新时间
                params.put("initUpdateTime", null);
            }
        }else{
            //预防保健
            if (ObjUtils.isNotEmpty(patientInit)) {
                if(ObjUtils.isNotEmpty(patientHistory) && ObjUtils.isNotEmpty(patientHistory.getAllergyHistory())
                        && ObjUtils.isNotEmpty(patientHistory.getUserHistory()) && ObjUtils.isNotEmpty(patientHistory.getMedicineHistory())
                        && ObjUtils.isNotEmpty(patientHistory.getFeverHistory())){
                    params.put("status", 2);
                    if (ObjUtils.isNotEmpty(patientTreatment)) {
                        params.put("status", 3);
                        if (ObjUtils.isNotEmpty(orderInfo)) {
                            params.put("status", 4);
                            if (pushList.size() > 0) {
                                params.put("status", 5);
                                if (orderInfo.getOrderState() == 0) {
                                    params.put("status", 6);
                                }
                            }
                        }
                    }
                    params.put("initUpdateTime", patientInit.get("createTime"));
                }else{
                    params.put("status", 1);
                    params.put("initUpdateTime", null);
                }
            }else{
                params.put("status", 1);
                params.put("initUpdateTime", null);
            }
        }


        if (ObjUtils.isNotEmpty(patientHistory)) {
            //病史档案更新时间
            params.put("historyUpdateTime", ObjUtils.isEmpty(patientHistory) ? null : patientHistory.getCreateTime());
        } else {
            //病史档案更新时间
            params.put("historyUpdateTime", null);
        }

        if (ObjUtils.isNotEmpty(patientTreatment)) {
            //患者病历更新时间
            params.put("treatmentUpdateTime", patientTreatment.getCreateTime());
        } else {
            //患者病历更新时间
            params.put("treatmentUpdateTime", null);
        }

        if (pushList.size() > 0) {
            //是否填写调查问卷 ： 0 未填写， 1 已填写
            params.put("isInput", 1);
        } else {
            params.put("isInput", 0);
        }

        return params;
    }

    @Override
    public Map<String, Object> selectTherapyScheduleState(Integer userId, Integer bookingId) {
        Map<String, Object> params = new HashMap<>();
        params.put("patientId", userId);
        params.put("bookingId", bookingId);
        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(bookingId);

        TPatientTreatment patientTreatment = patientTreatmentMapper.selectByMap(params);
        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);
        params.put("bookingId", null);

        List<TDoctorPushRel> pushList = doctorPushRelMapper.selectByMap(params);
        Map<String, Object> patientInit = patientInitMapper.selectByMap(params);
        TPatientHistory patientHistory = patientHistoryMapper.selectByPatientId(userId);
        params = new HashMap<>();

        // 1、判断病史档案是否填写
        if (ObjUtils.isNotEmpty(patientHistory) && ObjUtils.isNotEmpty(patientHistory.getAllergyHistory())
                && ObjUtils.isNotEmpty(patientHistory.getUserHistory()) && ObjUtils.isNotEmpty(patientHistory.getMedicineHistory())
                && ObjUtils.isNotEmpty(patientHistory.getFeverHistory())) {
            params.put("historyStatus", 1); // 已填写病史档案
        } else {
            params.put("historyStatus", 0); // 未填写病史档案
        }

        // 2、判断病历是否填写完整
        if ((ObjUtils.isNotEmpty(patientTreatment) && ObjUtils.isNotEmpty(patientTreatment.getTreatmentImg())
                && ObjUtils.isNotEmpty(patientTreatment.getHandsImg()) && ObjUtils.isNotEmpty(patientTreatment.getFaceImg())
                && ObjUtils.isNotEmpty(patientTreatment.getDiseaseInfo())) || bookingInfo.getBookingType() == 1) {
            params.put("treatmentStatus", 1); // 已填写病史档案
        } else {
            params.put("treatmentStatus", 0); // 未填写病史档案
        }

        // 3、判断订单是否创建
        if (ObjUtils.isNotEmpty(orderInfo)) {
            params.put("orderCreateStatus", 1); // 已创建
        } else {
            params.put("orderCreateStatus", 0); // 未创建
        }

        // 4、判断是否推送健康评估
        if (pushList.size() > 0) {
            params.put("pushStatus", 1); // 已推送
        } else {
            params.put("pushStatus", 0); // 未推送
        }

        // 5、判断订单是否完成
        if (ObjUtils.isNotEmpty(orderInfo) && orderInfo.getOrderState() == 0) {
            params.put("orderCompleteStatus", 1); // 已完成
        } else {
            params.put("orderCompleteStatus", 0); // 未完成
        }

        //病史档案更新时间
        params.put("historyUpdateTime", ObjUtils.isEmpty(patientHistory) || ObjUtils.isEmpty(patientHistory.getFeverHistory()) ? 0 : patientHistory.getCreateTime());

        //患者病历更新时间
        params.put("treatmentUpdateTime", ObjUtils.isEmpty(patientTreatment) ? 0 : patientTreatment.getUpdateTime());

        //基础信息调查表创建时间
        params.put("initUpdateTime", ObjUtils.isEmpty(patientInit) ? 0 : patientInit.get("createTime"));

        return params;
    }

    /**
     * 新增患者病历详情
     *
     * @param patientTreatment
     * @param pointArray
     * @param diseaseArray
     * @return
     */
    @Override
    public Integer saveTreatmentInfo(TPatientTreatment patientTreatment,String bookingName,String bookingPhone,String bookingPhones,
                                     Integer doctorId ,Integer subclinicId,String pointArray, String diseaseArray, String conclusionArray,
                                     String infoIds, Integer specialId, Integer checkResult, Integer realResult, Integer error) {

        Map<String, Object> params = new HashMap<>();
        Integer bookingId = patientTreatment.getBookingId();
        Integer patientId = patientTreatment.getPatientId();
        params.put("bookingId", bookingId);
        params.put("patientId", patientId);

        if(ObjUtils.isNotEmpty(bookingId)){
            TBookingInfo booking = bookingInfoMapper.selectByPrimaryKey(bookingId);
            if(ObjUtils.isNotEmpty(booking)){
                patientTreatment.setIsAdd(booking.getIsAdd());
                patientTreatment.setBookingType(booking.getBookingType());
                patientTreatment.setDegreeId(booking.getDegreeId());
            }
        }
        params.put("bookingId", bookingId);
        params.put("patientId", patientId);
        params.put("userId", patientTreatment.getUserId());

        Integer diseaseScore = 0,treatmentId = 0;

        TPatientTreatment patientTreatments = patientTreatmentMapper.selectByPatientIdAndBookingId(params);
        if (ObjUtils.isEmpty(patientTreatment.getTreatmentId())) {
            patientTreatmentMapper.insertSelective(patientTreatment);
            treatmentId = patientTreatment.getTreatmentId();
        } else {
            treatmentId = patientTreatments.getTreatmentId();

            patientTreatments.setBookingId(bookingId);
            patientTreatments.setPatientId(patientId);
            patientTreatments.setDiseaseTime(patientTreatment.getDiseaseTime());
            patientTreatments.setDiseaseInfo(patientTreatment.getDiseaseInfo());
            patientTreatments.setTreatmentInit(patientTreatment.getTreatmentInit());
            patientTreatments.setTreatmentOpinion(patientTreatment.getTreatmentOpinion());
            patientTreatments.setTreatmentRemarks(patientTreatment.getTreatmentRemarks());
            patientTreatments.setTreatmentImg(patientTreatment.getTreatmentImg());
            patientTreatmentMapper.updateByPrimaryKeySelective(patientTreatments);
        }

        params.put("bookingId", null);
        Map<String, Object> patientInitMap = patientInitMapper.selectByMap(params);
        TPatientInit patientInit = new TPatientInit();
        patientInit.setPatientId(patientId);
        patientInit.setTherapyStatus(3);
        patientInit.setRelId(Integer.parseInt(patientInitMap.get("relId").toString()));
        patientInitMapper.updateByPrimaryKeySelective(patientInit);

        //保存病症程度
        JSONArray diseaseArrays = JSONArray.fromObject(diseaseArray);

        TPatientTreatment treatment = patientTreatmentMapper.selectByPrimaryKey(treatmentId);

        for (int i = 0; i < diseaseArrays.size(); i++) {
            JSONObject jsonObject = diseaseArrays.getJSONObject(i);
            TUserDiseaseRel diseaseInfo = new TUserDiseaseRel();

            diseaseInfo.setUserId(treatment.getUserId());
            diseaseInfo.setBookingId(treatment.getBookingId());
            diseaseInfo.setPatientId(treatment.getPatientId());
            diseaseInfo.setDoctorId(doctorId);
            diseaseInfo.setTreatmentId(treatmentId);
            diseaseInfo.setTypeId(jsonObject.optInt("typeId"));
            diseaseInfo.setDiseaseId(jsonObject.optInt("diseaseId"));
            diseaseInfo.setTypeName(jsonObject.optString("typeName"));
            diseaseInfo.setDiseaseName(jsonObject.optString("diseaseName"));
            diseaseInfo.setIsMain(jsonObject.optInt("isMain"));
            diseaseInfo.setDiseaseScore(jsonObject.optInt("diseaseScore"));
            diseaseInfo.setSubclinicId(subclinicId);
            if(diseaseInfo.getIsMain() == 1){
                diseaseScore += (10 - jsonObject.optInt("diseaseScore"));
            }
            userDiseaseRelMapper.insertSelective(diseaseInfo);
        }

        //保存特病相关信息
        if (!(checkResult == null && realResult == null && error == null)) {
            initRecordAnswerMapper.deleteRecordAnswerByTreatmentId(treatmentId);
        }

        if (infoIds != null && !infoIds.equals("[]")){
            Map<String, Object> specialParams = new HashMap<>();
            specialParams.put("userId", patientTreatment.getUserId());
            specialParams.put("patientId", patientId);
            specialParams.put("treatmentId", treatmentId);
            specialParams.put("doctorId", doctorId);
            JSONArray infoIdArrays = JSONArray.fromObject(infoIds);
            List<Integer> infoIdList = new ArrayList<>();
            for (int i = 0; i < infoIdArrays.size(); i++) {
                infoIdList.add(infoIdArrays.getInt(i));
            }
            specialParams.put("infoIds", infoIdList);
            initRecordAnswerMapper.insertRecordAnswer(specialParams);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("specialId", specialId);
        hashMap.put("specialCheckScore", checkResult);
        hashMap.put("specialRealScore", realResult);
        hashMap.put("specialError", error);
        hashMap.put("treatmentId", treatmentId);
        if (!(checkResult == null && realResult == null && error == null)) {
            patientTreatmentMapper.updateByTreatmentId(hashMap);
        }

        //保存初始治愈率基础数据
        TUserTreatmentRel treatmentRel = new TUserTreatmentRel();
        treatmentRel.setDoctorId(doctorId);
        treatmentRel.setTreatmentRatio(new BigDecimal(0.0));
        treatmentRel.setSumValue(150 - diseaseScore);
        treatmentRel.setTreatmentId(treatmentId);
        userTreatmentRelMapper.insertSelective(treatmentRel);

        //保存穴位相关信息
        JSONArray pointArrays = JSONArray.fromObject(pointArray);
        for (int i = 0; i < pointArrays.size(); i++) {
            JSONObject jsonObject = pointArrays.getJSONObject(i);
            TUserPointRel pointInfo = new TUserPointRel();
            pointInfo.setUserId(treatment.getUserId());
            pointInfo.setBookingId(treatment.getBookingId());
            pointInfo.setPatientId(treatment.getPatientId());
            pointInfo.setDoctorId(doctorId);
            pointInfo.setTypeId(jsonObject.optInt("typeId"));
            pointInfo.setPointId(jsonObject.optInt("pointId"));
            pointInfo.setTypeName(jsonObject.optString("typeName"));
            pointInfo.setPointName(jsonObject.optString("pointName"));
            pointInfo.setSubclinicId(subclinicId);
            userPointRelMapper.insertSelective(pointInfo);
        }

        JSONArray conclusionArrays = JSONArray.fromObject(conclusionArray);
        for (int i = 0; i < conclusionArrays.size(); i++) {
            JSONObject jsonObject = conclusionArrays.getJSONObject(i);
            TUserConclusionRel conclusionRel = new TUserConclusionRel();
            conclusionRel.setUserId(treatment.getUserId());
            conclusionRel.setBookingId(treatment.getBookingId());
            conclusionRel.setPatientId(treatment.getPatientId());
            conclusionRel.setDoctorId(doctorId);
            conclusionRel.setConclusionId(jsonObject.optInt("conclusionId"));
            conclusionRel.setConclusionName(jsonObject.optString("conclusionName"));
            conclusionRel.setSubclinicId(subclinicId);
            conclusionRelMapper.insertSelective(conclusionRel);
        }

        params = new HashMap<>();
        params.put("bookingId", bookingId);
        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);
        if (ObjUtils.isNotEmpty(orderInfo) && orderInfo.getOrderState() == 0) { // 已完成
            patientTreatment.setTreatmentState(1);
            patientTreatmentMapper.updateByPrimaryKeySelective(patientTreatment);

            // 计算医生提成
            calculateDoctorSale(orderInfo);
        }

        return treatmentId;
    }

    /**
     * 修改
     *
     * @param patientTreatment
     * @param pointArray
     * @param diseaseArray
     * @return
     */
    @Override
    public Integer updateTreatmentInfo(TPatientTreatment patientTreatment, String pointArray, String diseaseArray, String conclusionArray,
                                       String infoIds, Integer specialId, Integer checkResult, Integer realResult, Integer error) {

        TPatientTreatment patientTreatments = patientTreatmentMapper.selectByPrimaryKey(patientTreatment.getTreatmentId());
        if (patientTreatments.getTreatmentState() == 1 || patientTreatments.getTreatmentState() == 2) {
            return -2; // 订单已完成或已过期，无法编辑
        }

        int count = 0;

        if (ObjUtils.isEmpty(patientTreatments)) {
            return count;
        }
        Integer diseaseScore = 0;
        Integer patientId = patientTreatment.getPatientId();
        Integer treatmentId = patientTreatment.getTreatmentId();

        if(ObjUtils.isEmpty(patientId)){
            patientTreatment.setPatientId(patientTreatments.getPatientId());
        }

        Integer bookingId = patientTreatments.getBookingId();
        if (ObjUtils.isNotEmpty(bookingId)) {
            Map<String, Object> bookingMap = new HashMap<>();
            bookingMap.put("bookingId", bookingId);
            TOrderInfo bookingOrder = orderInfoMapper.selectByMap(bookingMap);
            if (ObjUtils.isNotEmpty(bookingOrder) && bookingOrder.getOrderState() == 0) { // 已完成
                if (patientTreatments.getTreatmentState() == 0) {
                    patientTreatment.setTreatmentState(1);
                    // 计算医生提成
                    calculateDoctorSale(bookingOrder);
                }
            }
        }

        count += patientTreatmentMapper.updateByPrimaryKeySelective(patientTreatment);
        count += userDiseaseRelMapper.deleteByBookingId(patientTreatment.getBookingId());
        count += userPointRelMapper.deleteByBookingId(patientTreatment.getBookingId());
        count += conclusionRelMapper.deleteByBookingId(patientTreatment.getBookingId());
        //保存病症程度
        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(patientTreatments.getBookingId());

        JSONArray diseaseArrays = JSONArray.fromObject(diseaseArray);
        for (int i = 0; i < diseaseArrays.size(); i++) {
            JSONObject jsonObject = diseaseArrays.getJSONObject(i);
            TUserDiseaseRel diseaseInfo = new TUserDiseaseRel();
            diseaseInfo.setTreatmentId(treatmentId);
            diseaseInfo.setUserId(patientTreatment.getUserId());
            diseaseInfo.setBookingId(patientTreatment.getBookingId());
            diseaseInfo.setPatientId(patientId);
            diseaseInfo.setDoctorId(bookingInfo.getDoctorId());
            diseaseInfo.setTypeId(jsonObject.optInt("typeId"));
            diseaseInfo.setDiseaseId(jsonObject.optInt("diseaseId"));
            diseaseInfo.setTypeName(jsonObject.optString("typeName"));
            diseaseInfo.setDiseaseName(jsonObject.optString("diseaseName"));
            diseaseInfo.setIsMain(jsonObject.optInt("isMain"));
            diseaseInfo.setDiseaseScore(jsonObject.optInt("diseaseScore"));
            if(diseaseInfo.getIsMain() == 1){
                diseaseScore += (10 - jsonObject.optInt("diseaseScore"));
            }
            count += userDiseaseRelMapper.insertSelective(diseaseInfo);
        }

        TUserTreatmentRel treatmentRel = userTreatmentRelMapper.selectTreatmentFrontInfo(treatmentId);
        if(ObjUtils.isNotEmpty(treatmentRel)){
            //修改初始得分
            treatmentRel.setSumValue(150-diseaseScore);
            userTreatmentRelMapper.updateByPrimaryKeySelective(treatmentRel);
        }

        //保存特病相关信息
        if (!(checkResult == null && realResult == null && error == null)) {
            initRecordAnswerMapper.deleteRecordAnswerByTreatmentId(treatmentId);
        }

        if (infoIds != null && !infoIds.equals("[]")){
            Map<String, Object> specialParams = new HashMap<>();
            specialParams.put("userId", patientTreatment.getUserId());
            specialParams.put("patientId", patientId);
            specialParams.put("treatmentId", treatmentId);
            specialParams.put("doctorId", bookingInfo.getDoctorId());
            JSONArray infoIdArrays = JSONArray.fromObject(infoIds);
            List<Integer> infoIdList = new ArrayList<>();
            for (int i = 0; i < infoIdArrays.size(); i++) {
                infoIdList.add(infoIdArrays.getInt(i));
            }
            specialParams.put("infoIds", infoIdList);
            initRecordAnswerMapper.insertRecordAnswer(specialParams);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("specialId", specialId);
        hashMap.put("specialCheckScore", checkResult);
        hashMap.put("specialRealScore", realResult);
        hashMap.put("specialError", error);
        hashMap.put("treatmentId", treatmentId);
        if (!(checkResult == null && realResult == null && error == null)) {
            patientTreatmentMapper.updateByTreatmentId(hashMap);
        }

        //保存穴位相关信息
        JSONArray pointArrays = JSONArray.fromObject(pointArray);
        for (int i = 0; i < pointArrays.size(); i++) {
            JSONObject jsonObject = pointArrays.getJSONObject(i);
            TUserPointRel pointInfo = new TUserPointRel();
            pointInfo.setUserId(patientTreatment.getUserId());
            pointInfo.setBookingId(patientTreatment.getBookingId());
            pointInfo.setPatientId(patientTreatment.getPatientId());
            pointInfo.setDoctorId(bookingInfo.getDoctorId());
            pointInfo.setTypeId(jsonObject.optInt("typeId"));
            pointInfo.setTypeName(jsonObject.optString("typeName"));
            pointInfo.setPointId(jsonObject.optInt("pointId"));
            pointInfo.setPointName(jsonObject.optString("pointName"));
            count += userPointRelMapper.insertSelective(pointInfo);
        }

        //保存病症程度
        JSONArray conclusionArrays = JSONArray.fromObject(conclusionArray);
        for (int i = 0; i < conclusionArrays.size(); i++) {
            JSONObject jsonObject = conclusionArrays.getJSONObject(i);
            TUserConclusionRel conclusionRel = new TUserConclusionRel();
            conclusionRel.setUserId(patientTreatment.getUserId());
            conclusionRel.setBookingId(patientTreatment.getBookingId());
            conclusionRel.setPatientId(patientTreatment.getPatientId());
            conclusionRel.setDoctorId(bookingInfo.getDoctorId());
            conclusionRel.setConclusionId(jsonObject.optInt("conclusionId"));
            conclusionRel.setConclusionName(jsonObject.optString("conclusionName"));
            count += conclusionRelMapper.insertSelective(conclusionRel);
        }

        return count;
    }

    // 计算医生提成
    private void calculateDoctorSale (TOrderInfo bookingOrder) {
        // 给大夫结算提成
        String userName = userInfoMapper.selectByPrimaryKey(bookingOrder.getUserId()).getUserName();
        Map<String, Object> serviceParams = new HashMap<>();
        serviceParams.put("orderId", bookingOrder.getOrderId());
        String serviceName = "";
        BigDecimal saleRatio = new BigDecimal(0.25);
        BigDecimal saleMoney = new BigDecimal(0); //总提成

        List<TOrderServiceDetail> serviceList = orderServiceDetailMapper.selectByMap(serviceParams);
        if (serviceList.size() > 0) {
            for (TOrderServiceDetail serviceDetail : serviceList){
                saleMoney = saleMoney.add(serviceDetail.getServiceCost().multiply(new BigDecimal(saleRatio.doubleValue())));
                serviceName = serviceDetail.getServiceName();
            }
        }

        List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(serviceParams);
        if(goodsList.size() > 0 ){
            for (TOrderGoodsDetail goodsDetail : goodsList){
                saleMoney = saleMoney.add(goodsDetail.getGoodsSumIncome());
            }
        }

        AccountDoctorInfo beforeAccountDoctorInfo = accountDoctorInfoMapper.selectByOrderId(bookingOrder.getOrderId());
        if (ObjUtils.isEmpty(beforeAccountDoctorInfo)) {
            // 创建大夫提成流水
            AccountDoctorInfo doctorInfo = new AccountDoctorInfo();
            doctorInfo.setBookingId(bookingOrder.getBookingId());
            doctorInfo.setOrderId(bookingOrder.getOrderId());
            doctorInfo.setUserName(userName);
            doctorInfo.setDoctorId(bookingOrder.getDoctorId());
            doctorInfo.setDetailName(serviceName + "");
            doctorInfo.setOrderPayCost(saleMoney);
            accountDoctorInfoMapper.insertSelective(doctorInfo);
        } else { // 更新大夫提成流水
            beforeAccountDoctorInfo.setUserName(userName);
            beforeAccountDoctorInfo.setDetailName(serviceName + "");
            beforeAccountDoctorInfo.setOrderPayCost(saleMoney);
            accountDoctorInfoMapper.updateByPrimaryKeySelective(beforeAccountDoctorInfo);
        }

        bookingOrder.setDoctorCost(saleMoney);
        orderInfoMapper.updateByPrimaryKeySelective(bookingOrder);
    }

    /**
     * 查询患者病历详情
     *
     * @param bookingId 预约ID
     * @param patientId 患者id
     * @return
     */
    @Override
    public ResponseData selectTreatmentInfo(Integer bookingId, Integer patientId) {
        ResponseData data = new ResponseData();

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);
        params.put("bookingId", bookingId);
        //params.put("treatmentId", bookingId);

        TPatientTreatment patientTreatment = patientTreatmentMapper.selectByMap(params);

        if (ObjUtils.isEmpty(patientTreatment)) {
            data.setCodeEnum(CodeEnum.CODE_20005);
            return data;
        }
        List<TUserPointRel> pointRelList = userPointRelMapper.selectByBookingIdAndPatientId(params);

        List<TUserDiseaseRel> diseaseRelList = userDiseaseRelMapper.selectByBookingIdAndPatientId(params);

        List<TUserConclusionRel> conclusionList = conclusionRelMapper.selectByMap(params);
        params.put("bookingId", patientTreatment.getBookingId());
        List<TDoctorPushRel> pushList = doctorPushRelMapper.selectByMap(params);

        params = new HashMap<>();
        params.put("patientTreatment", patientTreatment);
        params.put("pointRelList", pointRelList);
        params.put("diseaseRelList", diseaseRelList);
        params.put("conclusionList", conclusionList);
        params.put("isPush", pushList.size() < 0 ? null : true);
        data.setResults(params);

        return data;
    }

    /**
     * 查询患者病历详情
     *
     * @param patientId 病历id
     * @return
     */
    @Override
    public ResponseData selectSysTreatmentInfo(Integer patientId,Integer treatmentId, Integer isOld,Integer bookingId) {
        ResponseData data = new ResponseData();

        Map<String, Object> params = new HashMap<>();
        TPatientTreatment patientTreatment;

        if(ObjUtils.isNotEmpty(isOld)){
            if(isOld == 1){
                //当前
                params.put("old", 1);
            }else{
                params.put("old", 0);
            }
        }


        if(ObjUtils.isNotEmpty(patientId)){
            params.put("patientId", patientId);
            params.put("bookingId", bookingId);
            patientTreatment = patientTreatmentMapper.selectByPatientIdAndBookingId(params);
        }else {
            patientTreatment = patientTreatmentMapper.selectByPrimaryKey(treatmentId);
        }

        if (ObjUtils.isEmpty(patientTreatment)) {
            data.setCodeEnum(CodeEnum.CODE_20005);
            return data;
        }
        params.put("bookingId", patientTreatment.getBookingId());
        params.put("patientId", patientTreatment.getPatientId());

        Map<String,Object> retMap = new HashMap<>();
        if(ObjUtils.isNotEmpty(patientTreatment)){

            //穴位
            List<TUserPointRel> pointRelList = userPointRelMapper.selectByBookingIdAndPatientId(params);
            List<TUserPointRel> pointList = userPointRelMapper.selectPointGroupConcat(params);
            //Map<Integer, List<TUserPointRel>> pointRelBy = pointRelList.stream().collect(Collectors.groupingBy(TUserPointRel::getTypeId));
            //病症
            List<TUserDiseaseRel> diseaseRelList = userDiseaseRelMapper.selectDiseaseGroupConcat(params);
            //诊断结论
            List<TUserConclusionRel> conclusionList = conclusionRelMapper.selectByMap(params);
            // 特病
            Map<String,Object> treatmentSpecialMap = patientTreatmentMapper.selectByTreatmentId(treatmentId);

            if (treatmentSpecialMap == null){
                treatmentSpecialMap = new HashMap<>();
                treatmentSpecialMap.put("specialRealScore",0);
                treatmentSpecialMap.put("specialCheckScore",0);
                treatmentSpecialMap.put("specialError",0);
            }
            treatmentSpecialMap.put("infoIds",initRecordAnswerMapper.selectRecordAll(treatmentId));

            //穴位
            retMap.put("pointList", pointRelList);
            retMap.put("pointRelList", pointList);//分组拼接字段
            //病症
            retMap.put("diseaseRelList", diseaseRelList);
            //诊断结论
            retMap.put("conclusionList", conclusionList);
            //病历
            retMap.put("patientTreatment", patientTreatment);
            //特病
            retMap.put("treatmentSpecialMap", treatmentSpecialMap);
        }else{
            //穴位
            retMap.put("pointList", null);
            retMap.put("pointRelList", null);//分组拼接字段
            //病症
            retMap.put("diseaseRelList", null);
            //诊断结论
            retMap.put("conclusionList", null);
            //病历
            retMap.put("patientTreatment", null);
            //特病
            retMap.put("treatmentSpecialMap", null);
        }

        data.setResults(retMap);

        return data;
    }

    /**
     * 获取患者历史病历列表
     *
     * @param patientId
     * @return
     */
    @Override
    public ResponseData selectHistoryTreatmentList(Integer patientId, ResponseData data) {

        data.setResults(patientTreatmentMapper.selectHistoryTreatmentList(patientId));

        return data;
    }

    /**
     * 提交订单
     *
     * @return
     */
    @Override
    public Integer saveOrderInfo(TOrderInfo orderInfo, String goodsList, String serviceList) {

        Integer count = 0;

        orderInfo.setOrderNo(ObjUtils.getOrderNo());

        Map<String, Object> params = new HashMap<>();
        params.put("bookingId", orderInfo.getBookingId());

        if (ObjUtils.isNotEmpty(orderInfo.getBookingId())) {
            TOrderInfo beforeOrder = orderInfoMapper.selectByMap(params);
            if (ObjUtils.isNotEmpty(beforeOrder)) {
                return -3;
            }
        }

        //params.put("patientId", orderInfo.getPatientId());
        params.put("orderState", 3);

        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(orderInfo.getBookingId()); // TreeJohn
        if(ObjUtils.isNotEmpty(orderInfo.getPatientId())){
            TPatientHistory history = patientHistoryMapper.selectByPatientId(orderInfo.getPatientId());
            if(bookingInfo.getBookingType().equals(0) && ObjUtils.isEmpty(history)){ // TreeJohn 预防保健可以不验证病史档案
                return -1;
            }

            //该预约单已产生订单，进行修改操作
            List<TOrderInfo> order = orderInfoMapper.selectOrderListByMap(params);

            if (order.size() > 0) {

                params.put("bookingId", null);
                params.put("patientId", order.get(0).getPatientId());
                Map<String,Object> init = patientInitMapper.selectByMap(params);

                if(ObjUtils.isEmpty(init.get("patientHeight")) && ObjUtils.isEmpty(init.get("patientBodyWeight"))){
                    return -2;
                }
                //修改订单
                if(ObjUtils.isNotEmpty(order.get(0))){
                    updateOrderDetail(order.get(0),goodsList,serviceList);
                }
            }
        }

        //保存病例病程 ， 预约类型， 是否上次治疗
        if(ObjUtils.isNotEmpty(bookingInfo)){
            //已预约单为主， 更新订单共有字段
            orderInfo.setDoctorId(bookingInfo.getDoctorId());
            orderInfo.setBookingId(bookingInfo.getBookingId());
            orderInfo.setUserId(bookingInfo.getUserId());
            orderInfo.setPatientId(bookingInfo.getPatientId());
            orderInfo.setSubclinicId(bookingInfo.getSubclinicId());
            orderInfo.setBookingType(bookingInfo.getBookingType());
            orderInfo.setIsAdd(bookingInfo.getIsAdd());
            orderInfo.setDegreeId(bookingInfo.getDegreeId());
        }

        orderInfo.setOrderState(3);
        if (null == orderInfo.getBookingId()){
            count += orderInfoMapper.insertSelective(orderInfo);
        }else{
            Map<String, Object> map = new HashMap<>();
            map.put("bookingId", orderInfo.getBookingId());
            if(null == orderInfoMapper.selectByMap(map)){
                count += orderInfoMapper.insertSelective(orderInfo);
            }
        }
        BigDecimal goodsMoney = new BigDecimal(0);

        if (ObjUtils.isNotEmpty(goodsList)) {
            JSONArray array = JSONArray.fromObject(goodsList);
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                TOrderGoodsDetail goodsDetail = new TOrderGoodsDetail();
                goodsDetail.setBookingId(orderInfo.getBookingId());
                goodsDetail.setOrderId(orderInfo.getOrderId());
                goodsDetail.setOrderNo(orderInfo.getOrderNo());
                goodsDetail.setUserId(orderInfo.getUserId());
                goodsDetail.setDoctorId(orderInfo.getDoctorId());
                goodsDetail.setSubclinicId(orderInfo.getSubclinicId());
                goodsDetail.setPatientId(orderInfo.getPatientId());
                goodsDetail.setGoodsId(jsonObject.optInt("goodsId"));
                goodsDetail.setGoodsName(jsonObject.optString("goodsName"));
                goodsDetail.setGoodsImg(jsonObject.optString("goodsImg"));
                goodsDetail.setGoodsCost(new BigDecimal(jsonObject.optDouble("goodsCost")));
                goodsDetail.setGoodsIncome(new BigDecimal(jsonObject.optDouble("goodsIncomeRatio")));
                goodsDetail.setOrderNum(jsonObject.optInt("orderNum"));
                //总价
                BigDecimal goodsCost = new BigDecimal(jsonObject.optDouble("goodsCost"));
                BigDecimal orderNum = new BigDecimal(goodsDetail.getOrderNum());
                goodsDetail.setGoodsSumCost(goodsCost.multiply(orderNum));
                //总提成
                BigDecimal goodsIncome = new BigDecimal(jsonObject.optDouble("goodsIncomeRatio"));
                goodsDetail.setGoodsSumIncome(goodsCost.multiply(goodsIncome).multiply(orderNum));

                goodsMoney = goodsMoney.add(goodsDetail.getGoodsSumCost());

                count += orderGoodsDetailMapper.insertSelective(goodsDetail);
            }
        }else{
            orderInfo.setPayWays(null);
        }

        BigDecimal serviceMoney = new BigDecimal(0);

        //推拿服务的提成是根据技师的等级来计算的
        SysUserInfo userInfo = sysUserInfoMapper.selectByPrimaryKey(orderInfo.getDoctorId());

        BigDecimal saleRatio = new BigDecimal(0);
//        if(userInfo.getUserLevel() == 1){
            saleRatio = saleRatio.add(new BigDecimal(0.25));
//        }
//        if(userInfo.getUserLevel() == 2){
//            saleRatio = saleRatio.add(new BigDecimal(0.26));
//        }
//        if(userInfo.getUserLevel() == 3){
//            saleRatio = saleRatio.add(new BigDecimal(0.27));
//        }
//        if(userInfo.getUserLevel() == 4){
//            saleRatio = saleRatio.add(new BigDecimal(0.28));
//        }
//        if(userInfo.getUserLevel() == 5){
//            saleRatio = saleRatio.add(new BigDecimal(0.29));
//        }


        if (ObjUtils.isNotEmpty(serviceList)) {
            JSONArray serviceArray = JSONArray.fromObject(serviceList);
            for (int i = 0; i < serviceArray.size(); i++) {
                JSONObject jsonObject = serviceArray.getJSONObject(i);
                TOrderServiceDetail serviceDetail = new TOrderServiceDetail();
                serviceDetail.setBookingId(orderInfo.getBookingId());
                serviceDetail.setOrderId(orderInfo.getOrderId());
                serviceDetail.setOrderNo(orderInfo.getOrderNo());
                serviceDetail.setUserId(orderInfo.getUserId());
                serviceDetail.setDoctorId(orderInfo.getDoctorId());
                serviceDetail.setSubclinicId(orderInfo.getSubclinicId());
                serviceDetail.setPatientId(orderInfo.getPatientId());
                serviceDetail.setServiceId(jsonObject.optInt("serviceId"));
                serviceDetail.setServiceImg(jsonObject.optString("serviceImg"));
                serviceDetail.setServiceName(jsonObject.optString("serviceName"));
                serviceDetail.setServiceCost(new BigDecimal(jsonObject.optDouble("serviceCost")));
                serviceDetail.setServiceIncome(serviceDetail.getServiceCost().multiply(saleRatio));
                count += orderServiceDetailMapper.insertSelective(serviceDetail);

                serviceMoney = serviceMoney.add(serviceDetail.getServiceCost());
            }
        }


        params.put("bookingId", null);
        Map<String, Object> patientInitMap = patientInitMapper.selectByMap(params);
        TPatientInit patientInit = new TPatientInit();
        patientInit.setRelId(Integer.parseInt(patientInitMap.get("relId").toString()));
        List<TDoctorPushRel> pushList = doctorPushRelMapper.selectByMap(params);
        if (pushList.size() > 0) {
            patientInit.setTherapyStatus(5);
        } else {
            patientInit.setTherapyStatus(4);
        }
        patientInitMapper.updateByPrimaryKeySelective(patientInit);

        if(ObjUtils.isNotEmpty(orderInfo.getBookingId())){

            bookingInfo.setBookingId(orderInfo.getBookingId());
            bookingInfo.setBookingStatus(3);
            bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
        }

        return orderInfo.getOrderId();
    }

    /**
     * 修改订单商品明细
     *
     * @param orderInfo
     * @param goodsList
     * @param serviceList
     * @return
     */
    @Override
    public Integer updateOrderDetail(TOrderInfo orderInfo, String goodsList, String serviceList) {

        Map<String, Object> params = new HashMap<>();

        TOrderInfo orderInfos = orderInfoMapper.selectByPrimaryKey(orderInfo.getOrderId());
        if (orderInfos.getOrderState() == 0) { // 已完成
            return -1;
        }

        if (ObjUtils.isEmpty(orderInfos)) {
            return 0;
        }
        orderInfo.setOrderId(orderInfos.getOrderId());
        orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

        //删除历史订单明细
        params.put("orderId",orderInfo.getOrderId());
        orderGoodsDetailMapper.deleteByMap(params);
        orderServiceDetailMapper.deleteByMap(params);
        //新增订单明细
        if (ObjUtils.isNotEmpty(goodsList)) {
            JSONArray array = JSONArray.fromObject(goodsList);
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                TOrderGoodsDetail goodsDetail = new TOrderGoodsDetail();
                goodsDetail.setBookingId(orderInfos.getBookingId());
                goodsDetail.setOrderId(orderInfos.getOrderId());
                goodsDetail.setOrderNo(orderInfos.getOrderNo());
                goodsDetail.setUserId(orderInfos.getUserId());
                goodsDetail.setDoctorId(orderInfos.getDoctorId());
                goodsDetail.setSubclinicId(orderInfos.getSubclinicId());
                goodsDetail.setPatientId(orderInfos.getPatientId());
                goodsDetail.setGoodsId(jsonObject.optInt("goodsId"));
                goodsDetail.setGoodsName(jsonObject.optString("goodsName"));
                goodsDetail.setGoodsImg(jsonObject.optString("goodsImg"));
                goodsDetail.setGoodsCost(new BigDecimal(jsonObject.optDouble("goodsCost")));
                goodsDetail.setGoodsIncome(new BigDecimal(jsonObject.optDouble("goodsIncomeRatio")));
                goodsDetail.setOrderNum(jsonObject.optInt("orderNum"));
                //总价
                BigDecimal goodsCost = new BigDecimal(jsonObject.optDouble("goodsCost"));
                BigDecimal orderNum = new BigDecimal(goodsDetail.getOrderNum());
                BigDecimal goodSumsCost = new BigDecimal(0);
                goodSumsCost = goodsCost.multiply(orderNum);
//                System.out.println("goodSumsCost = " + goodSumsCost);
                goodsDetail.setGoodsSumCost(goodSumsCost);
                //总提成
                BigDecimal goodsIncome = new BigDecimal(jsonObject.optDouble("goodsIncomeRatio"));
                goodsDetail.setGoodsSumIncome(goodsCost.multiply(goodsIncome).multiply(orderNum));

                orderGoodsDetailMapper.insertSelective(goodsDetail);
            }
        }

        //推拿服务的提成是根据技师的等级来计算的
        SysUserInfo userInfo = sysUserInfoMapper.selectByPrimaryKey(orderInfo.getDoctorId());

        BigDecimal saleRatio = new BigDecimal(0);
//        if(userInfo.getUserLevel() == 1){
            saleRatio = saleRatio.add(new BigDecimal(0.25));
//        }
//        if(userInfo.getUserLevel() == 2){
//            saleRatio = saleRatio.add(new BigDecimal(0.26));
//        }
//        if(userInfo.getUserLevel() == 3){
//            saleRatio = saleRatio.add(new BigDecimal(0.27));
//        }
//        if(userInfo.getUserLevel() == 4){
//            saleRatio = saleRatio.add(new BigDecimal(0.28));
//        }
//        if(userInfo.getUserLevel() == 5){
//            saleRatio = saleRatio.add(new BigDecimal(0.29));
//        }

        if (ObjUtils.isNotEmpty(serviceList)) {
            JSONArray serviceArray = JSONArray.fromObject(serviceList);
            for (int i = 0; i < serviceArray.size(); i++) {
                JSONObject jsonObject = serviceArray.getJSONObject(i);
                TOrderServiceDetail serviceDetail = new TOrderServiceDetail();
                serviceDetail.setBookingId(orderInfos.getBookingId());
                serviceDetail.setOrderId(orderInfos.getOrderId());
                serviceDetail.setOrderNo(orderInfos.getOrderNo());
                serviceDetail.setUserId(orderInfos.getUserId());
                serviceDetail.setDoctorId(orderInfos.getDoctorId());
                serviceDetail.setSubclinicId(orderInfos.getSubclinicId());
                serviceDetail.setPatientId(orderInfos.getPatientId());
                serviceDetail.setServiceId(jsonObject.optInt("serviceId"));
                serviceDetail.setServiceImg(jsonObject.optString("serviceImg"));
                serviceDetail.setServiceName(jsonObject.optString("serviceName"));
                serviceDetail.setServiceCost(new BigDecimal(jsonObject.optDouble("serviceCost")));
                serviceDetail.setServiceIncome(new BigDecimal(jsonObject.optDouble("serviceIncome")));

                BigDecimal serviceCost = new BigDecimal(jsonObject.optDouble("serviceCost"));
                BigDecimal orderNum = new BigDecimal(1);
                BigDecimal serviceSumCost = new BigDecimal(0);
                serviceSumCost = serviceCost.multiply(orderNum);

                serviceDetail.setServiceIncome(serviceDetail.getServiceCost().multiply(saleRatio));
                serviceDetail.setServiceSumCost(serviceSumCost);
                System.out.println("serviceSumCost = " + serviceSumCost);
                orderServiceDetailMapper.insertSelective(serviceDetail);
            }
        }
        return 1;
    }

    /**
     * 查询订单
     *
     * @param bookingId
     * @param patientId
     * @return
     */
    @Override
    public Map<String, Object> selectOrderInfo(Integer bookingId, Integer patientId) {

        Map<String, Object> params = new HashMap<>();
        params.put("bookingId", bookingId);
        params.put("patientId", patientId);

        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);

        List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(params);

        List<TOrderServiceDetail> serviceList = orderServiceDetailMapper.selectByMap(params);
        params = new HashMap<>();

        params.put("goodsList", goodsList);
        params.put("serviceList", serviceList);
        params.put("orderId", ObjUtils.isEmpty(orderInfo) ? null : orderInfo.getOrderId());
        params.put("couponId", ObjUtils.isEmpty(orderInfo) ? null : orderInfo.getCouponId());

        return params;
    }

    /**
     * 查询订单详情
     *
     * @param bookingId
     * @param patientId
     * @return
     */
    @Override
    public ResponseData selectOrderDetail(Integer bookingId, Integer patientId, Integer orderId, ResponseData data) {

        Map<String, Object> params = new HashMap<>();
        params.put("bookingId", bookingId);
        params.put("patientId", patientId);
        params.put("orderId", orderId);
        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);

        if (ObjUtils.isEmpty(orderInfo)) {
            data.setCodeEnum(CodeEnum.CODE_30001);
            return data;
        }
        Map<String, Object> orderMap = orderInfoMapper.selectOrderDetail(params);

        List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(params);

        List<TOrderServiceDetail> serviceList = orderServiceDetailMapper.selectByMap(params);
        params = new HashMap<>();

        params.put("goodsList", goodsList);
        params.put("serviceList", serviceList);
        params.put("orderInfo", orderMap);

        data.setResults(params);
        return data;
    }

    /**
     * 修改订单-
     *
     * @param bookingId
     * @param patientId
     * @param orderStatus
     * @return
     */
    @Override
    public Integer updateOrderInfo(Integer bookingId, Integer patientId, Integer orderStatus) {

        Map<String, Object> params = new HashMap<>();
        params.put("bookingId", bookingId);
        params.put("patientId", patientId);
        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(bookingId);
        TOrderInfo orderInfo = orderInfoMapper.selectByMap(params);

        TPatientHistory history = patientHistoryMapper.selectByPatientId(bookingInfo.getPatientId());
        if(orderStatus != 4 && bookingInfo.getBookingType().intValue() == 0 && ObjUtils.isEmpty(history)){
            return -1;
        }

        //bookingInfo.setBookingStatus(4);
        //bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
        //订单状态:0:完成;1:未接诊;2:调理中;3:待支付;4:已关闭
        if(ObjUtils.isNotEmpty(bookingInfo)){
            //订单完成
            if (orderStatus == 0) {
                if (ObjUtils.isNotEmpty(bookingInfo)) {
                    bookingInfo.setBookingStatus(4);
                    bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
                }
            }
            //结束调理，订单待支付
            if (orderStatus == 3) {
                if (ObjUtils.isNotEmpty(bookingInfo)) {
                    params.put("bookingId", null);
                    //修改基础调查信息表状态为 ： 6
                    Map<String, Object> patientInitMap = patientInitMapper.selectByMap(params);
                    TPatientInit patientInit = new TPatientInit();
                    patientInit.setRelId(Integer.parseInt(patientInitMap.get("relId").toString()));
                    patientInit.setTherapyStatus(6);
                    patientInitMapper.updateByPrimaryKeySelective(patientInit);

                    bookingInfo.setBookingStatus(3);
                    bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);

//                    if(ObjUtils.isNotEmpty(bookingInfo.getBookingType())){
//                        //当用户预约时预约类型时预防保健 - 更改为调理身体后 - 病例信息为空
//                        if(bookingInfo.getBookingType() == 1){
//
//                            params.put("bookingId", bookingInfo.getBookingId());
//
//                            TPatientTreatment treatment = patientTreatmentMapper.selectByMap(params);
//
//                            if(ObjUtils.isEmpty(treatment.getDiseaseInfo()) ||
//                                    ObjUtils.isEmpty(treatment.getDiseaseTime())){
//                                return -2;
//                            }
//                        }
//                    }

                }
            }
            //关闭订单
            if (orderStatus == 4) {
                if (ObjUtils.isNotEmpty(bookingInfo)) {
                    bookingInfo.setBookingStatus(5);
                    bookingInfo.setCancelTime(new Date());
                    bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);

                    // 取消预约给客户发微信推送，给大夫发短信提醒
                    TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(bookingInfo.getUserId());
                    SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(bookingInfo.getDoctorId());
                    TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectByPrimaryKey(bookingInfo.getSubclinicId());
                    TPatientInfo patient = patientInfoMapper.selectByPrimaryKey(bookingInfo.getPatientId());

                    ICommonService.cancleBookingPushAndMessage(bookingInfo, userInfo, sysUserInfo, subclinicInfo, patient);
                }
            }
            if(ObjUtils.isNotEmpty(orderInfo)){
                orderInfo.setOrderState(orderStatus);
                orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
            }

        }

        return 1;
    }

    @Override
    public Map<String, Object> selectUserInfo(Integer doctorId, ResponseData data) {

        Map<String, Object> retMap = new HashMap<>();

        SysUserInfo userInfo = sysUserInfoMapper.selectByPrimaryKey(doctorId);

        if (ObjUtils.isEmpty(userInfo)) {
            return retMap;
        }
        retMap.put("userInfo", userInfo);

//        //查询用户订单总数
        Integer doctorOrderCount = orderInfoMapper.selectDoctorOrderCount(doctorId);
        //获取当前等级
        InitGradeDoctor gradeDoctor = gradeDoctorMapper.selectDoctorGrade(doctorOrderCount);
//        gradeDoctor.setGradeStartScore(doctorOrderCount);
        retMap.put("gradeName", gradeDoctor.getGradeName());
//        //下一级所需要多少分
//        retMap.put("score", gradeDoctor.getGradeEndScore() - doctorOrderCount);
        data.setResults(retMap);
        return retMap;
    }

    /**
     * 查询大夫提成明细
     *
     * @param doctorId
     * @return
     */
    @Override
    public Map<String, Object> selectUserSaleList(Integer doctorId) {

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("doctorId", doctorId);
//        retMap.put("monthStr", DateUtils.format(new Date(),DateUtils.YYYY_MM_DD));
        List<Map<String, Object>> saleList = orderInfoMapper.selectDoctorSaleList(retMap);

        BigDecimal sumSale = new BigDecimal(0);

        for (Map<String, Object> saleMap : saleList) {

            if(ObjUtils.isNotEmpty(saleMap.get("goodsName"))){
                saleMap.put("goodsName", "就诊订单");
            }else{
                saleMap.put("goodsName", "商品订单");
            }

            BigDecimal goodsIncome = new BigDecimal(saleMap.get("goodsIncome").toString());
            sumSale = sumSale.add(goodsIncome);
        }

        retMap.put("saleList", saleList);
        retMap.put("sumSale", sumSale);
        return retMap;
    }

    /**
     * 查询可休息的日期
     *
     * @param doctorId
     * @return
     */
    @Override
    public List<Map<String, Object>> selectDoctorRest(Integer doctorId, String offDay) {

        Map<String, Object> params = new HashMap<>();
        params.put("doctorId", doctorId);
        params.put("offDay", offDay);

        return offInfoMapper.selectDoctorRest(params);
    }


    /**
     * 统计接口
     *
     * @param doctorId
     * @return
     */
    @Override
    public ResponseData selectStatistics(Integer doctorId, String monthStr, ResponseData data) {

        Map<String, Object> retMap = new HashMap<>();

        SysUserInfo userInfo = sysUserInfoMapper.selectByPrimaryKey(doctorId);

        if (ObjUtils.isEmpty(userInfo)) {
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }

        retMap.put("userInfo", userInfo);
        retMap.put("doctorId", doctorId);
        retMap.put("monthStr", monthStr);
        List<Map<String, Object>> saleList = orderInfoMapper.selectDoctorSaleList(retMap);
        //业绩列表
        //Integer orderNumber = orderInfoMapper.selectDoctorOrderCount(doctorId);
        retMap.put("saleList", saleList);
        retMap.put("saleListSize", saleList.size());
        BigDecimal saleCost = new BigDecimal(0);

        for (Map<String, Object> saleMap : saleList) {
            saleCost = saleCost.add(new BigDecimal(saleMap.get("goodsIncome").toString()));
        }
        retMap.put("saleCost", saleCost);

        try {
            List<TOffInfo> offList = offInfoMapper.selectDoctorOffList(doctorId, monthStr);

            Date date = DateUtils.parse(monthStr, "yyyy-MM");
            List<String> dayList = DateUtils.getMonthDateList(date);
            List<String> offListStr = new ArrayList<>();
            if (ObjUtils.isNotEmpty(offList)) {

                for (TOffInfo offInfo : offList) {

                    remove(dayList, offInfo.getOffDay());

                    offListStr.add(offInfo.getOffDay());
                }
            }
            //休息日集合
            retMap.put("offListStr", offListStr);
            retMap.put("offListSize", offListStr.size());
            //工作日集合
            retMap.put("workList", dayList);
            retMap.put("workListSize", dayList.size());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        data.setResults(retMap);

        return data;
    }

    /**
     * 查询医师订单列表
     *
     * @param doctorId
     * @return
     */
    @Override
    public List<TOrderInfo> selectDoctorOrderList(Integer doctorId) {

        Map<String, Object> params = new HashMap<>();
        params.put("doctorId", doctorId);
        List<TOrderInfo> orderList = orderInfoMapper.selectOrderListByMap(params);
        return orderList;
    }

    /**
     * 修改密码
     *
     * @param params
     * @return
     */
    @Override
    public int updateUserPwd(Map<String, Object> params) {

        Integer userId = Integer.parseInt(params.get("doctorId").toString());
        String userPwd = params.get("userPwd").toString();
        //新建Mapper参数
        Map<String, Object> newParams = new HashMap<>();
        newParams.put("userId", userId);
        //新密码格式
        if (6 <= userPwd.length() && userPwd.length() <= 20) {
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(userId);
            if (ObjUtils.isNotEmpty(sysUserInfo)) {
                //如果密码不为空
                if (ObjUtils.isNotEmpty(sysUserInfo.getUserPwd())) {
                    // 如果密码匹配成功
                    if (MD5Utils.md5Password(userPwd).equals(sysUserInfo.getUserPwd())) {
                        // 修改密码
                        newParams.put("userPwd", MD5Utils.md5Password(params.get("newPwd").toString()));
                        int count = sysUserInfoMapper.updateStatusByKey(newParams);
                        return count;
                    } else {
                        // 否则说明密码错误
                        return -1;
                    }
                }
                return -3;//参数不正确
            }
            return -2;//无此用户
        } else {
            return -1;//密码不正确
        }
    }

    /**
     * 修改预约状态
     *
     * @param bookingId
     * @return
     */
    @Override
    public Integer updateBookingState(Integer bookingId) {

        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(bookingId);

        if(ObjUtils.isEmpty(bookingInfo)){
            return 0;
        }
        //当前状态:0:待就诊;1:已迟到;2:调理中;3:待支付;4:已完成;5:取消;6:已接诊
        if(bookingInfo.getBookingStatus() == 0){
            bookingInfo.setBookingStatus(6);
        }
        //新增预约类型：  0:调理身体 , 1:预防保健
        if(bookingInfo.getBookingType() == 1){

            Map<String,Object> params = new HashMap<>();
            params.put("patientId", bookingInfo.getPatientId());
            params.put("bookingId", bookingId);

            TPatientTreatment treatment = patientTreatmentMapper.selectByMap(params);
            if(ObjUtils.isEmpty(treatment)){

                TPatientTreatment patientTreatment = new TPatientTreatment();
                patientTreatment.setBookingId(bookingId);
                patientTreatment.setDegreeId(bookingInfo.getDegreeId());
                patientTreatment.setPatientId(bookingInfo.getPatientId());
                patientTreatment.setUserId(bookingInfo.getUserId());
                patientTreatment.setIsAdd(bookingInfo.getIsAdd());
                patientTreatment.setBookingType(bookingInfo.getBookingType());
                //保存一个病例
                patientTreatmentMapper.insertSelective(patientTreatment);

//            Map<String,Object> params = new HashMap<>();
//            params.put("patientId", bookingInfo.getPatientId());
//            Map<String, Object> patientInitMap = patientInitMapper.selectByMap(params);
//            TPatientInit patientInit = new TPatientInit();
//            patientInit.setPatientId(patientTreatment.getPatientId());
//            patientInit.setTherapyStatus(5);
//            patientInit.setRelId(Integer.parseInt(patientInitMap.get("relId").toString()));
//            patientInitMapper.updateByPrimaryKeySelective(patientInit);
            }

        }
        //新增继续上次预约还是开启新病程

        return bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
    }

    @Override
    public Integer updateByTreatmentId(HashMap<String, Object> params) {
        return patientTreatmentMapper.updateByTreatmentId(params);
    }

    @Override
    public Integer updateOrderInfoByPayFlag(Integer payWay, Integer payWays, Integer orderId) {
        TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (payWay == orderInfo.getPayWay() && payWays == orderInfo.getPayWays()) {
            return -1; // 支付方式未变化
        }

        if (payWay == 7 || payWays == 7) {
            return -2; // 代付无法修改支付方式
        }

        if (orderInfo.getOrderState() != 0) {
            return -3; // 未完成订单不能修改支付方式
        }

        int type;
        TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId());
        BigDecimal orderTotalCost = orderInfo.getOrderTotalCost(); // 订单金额
        BigDecimal userBeforeAccount = userInfo.getUserAccount(); // 用户更新前余额
        BigDecimal balancePayCost = orderInfo.getBalancePayCost();

        if (payWay == 0 && payWays == 0) { // 改成都余额
            if (orderInfo.getPayWay() != 0 && orderInfo.getPayWays() != 0) { // 原都非余额 -> 都余额
                // 扣余额：用户余额 - 订单金额; balance_pay_cost = 订单金额

                if (userBeforeAccount.subtract(orderTotalCost).doubleValue() < 0) {
                    return -4; // 余额不足
                } else {
                    setUserAccountAndUpdateUser(userBeforeAccount.subtract(orderTotalCost), userInfo);
                    setBalancePayCostAndUpdateOrder(orderTotalCost, orderInfo, payWay);
                }
                type = 1;
            } else if ((orderInfo.getPayWay() != 0 && orderInfo.getPayWays() == 0) // 原推拿非余额 -> 都余额
                    || (orderInfo.getPayWay() == 0 && orderInfo.getPayWays() != 0)) { // 原商品非余额 -> 都余额
                // 扣余额：用户余额 - (订单金额 — balance_pay_cost); balance_pay_cost = 订单金额
                BigDecimal shouldPayCost = orderTotalCost.subtract(balancePayCost);

                if (userBeforeAccount.subtract(shouldPayCost).doubleValue() < 0) {
                    return -4; // 余额不足
                } else {
                    setUserAccountAndUpdateUser(userBeforeAccount.subtract(shouldPayCost), userInfo);
                    setBalancePayCostAndUpdateOrder(orderTotalCost, orderInfo, payWay);
                }
                type = 23;
            } else { // 支付方式没变，已排除
                type = 4;
            }
        } else if (payWay != 0 && payWays != 0) { // 改成都非余额
            if (orderInfo.getPayWay() == 0 && orderInfo.getPayWays() == 0) { // 原都余额 -> 都非余额
                // 加余额：用户余额 + 订单金额
                setUserAccountAndUpdateUser(userBeforeAccount.add(orderTotalCost), userInfo);
                setBalancePayCostAndUpdateOrder(new BigDecimal(0), orderInfo, payWay);
                type = 5;
            } else if (orderInfo.getPayWay() == 0 && orderInfo.getPayWays() != 0 // 原推拿余额 -> 都非余额
                    || orderInfo.getPayWay() != 0 && orderInfo.getPayWays() == 0) { // 原商品余额 -> 都非余额
                // 加余额：用户余额 + balance_pay_cost; balance_pay_cost = 0
                setUserAccountAndUpdateUser(userBeforeAccount.add(balancePayCost), userInfo);
                setBalancePayCostAndUpdateOrder(new BigDecimal(0), orderInfo, payWay);
                type = 67;
            } else { // 支付方式不涉及余额，不需要处理
                type = 8;
            }
        } else { // 改成其中一个为余额
            if (payWay == 0) {
                if (orderInfo.getPayWays() == 0) {
                    if (orderInfo.getPayWay() == 0) { // 都余额 -> 推余额
                        BigDecimal serviceCost = selectServiceCost(orderId); // 推拿金额
                        BigDecimal goodsCost = balancePayCost.subtract(serviceCost); // 余额变化

                        setUserAccountAndUpdateUser(userBeforeAccount.add(goodsCost), userInfo);
                        setBalancePayCostAndUpdateOrder(serviceCost, orderInfo, payWay); // 推拿金额
                        type = 90;
                    } else { // 原推拿非余额，商余额 -> 推余额
                        int option = optionUpdate(orderTotalCost, balancePayCost, userBeforeAccount, orderInfo, userInfo, payWay);
                        if (option < 0) {
                            return option; // -4
                        }
                        type = 91;
                    }
                } else { // 都非余额 -> 推余额
                    BigDecimal serviceCost = selectServiceCost(orderId); // 推拿金额

                    if (userBeforeAccount.subtract(serviceCost).doubleValue() < 0) {
                        return -4; // 余额不足
                    } else {
                        setUserAccountAndUpdateUser(userBeforeAccount.subtract(serviceCost), userInfo);
                        setBalancePayCostAndUpdateOrder(serviceCost, orderInfo, payWay); // 推拿金额
                    }
                    type = 92;
                }
            } else { // payWays == 0
                if (orderInfo.getPayWay() == 0) {
                    if (orderInfo.getPayWay() == 0) { // 都余额 -> 商品余额
                        BigDecimal serviceCost = selectServiceCost(orderId); // 推拿金额
                        BigDecimal goodsCost = balancePayCost.subtract(serviceCost); // 余额变化

                        setUserAccountAndUpdateUser(userBeforeAccount.add(serviceCost), userInfo);
                        setBalancePayCostAndUpdateOrder(goodsCost, orderInfo, payWay); // 推拿金额
                        type = 100;
                    } else { // 原商品非余额，推余额 -> 商品余额
                        int option = optionUpdate(orderTotalCost, balancePayCost, userBeforeAccount, orderInfo, userInfo, payWay);
                        if (option < 0) {
                            return option; // -4
                        }
                        type = 101;
                    }
                } else { // 都非余额 -> 商品余额
                    BigDecimal serviceCost = selectServiceCost(orderId); // 推拿金额
                    BigDecimal goodsCost = orderInfo.getOrderTotalCost().subtract(serviceCost); // 商品金额

                    if (userBeforeAccount.subtract(goodsCost).doubleValue() < 0) {
                        return -4; // 余额不足
                    } else {
                        setUserAccountAndUpdateUser(userBeforeAccount.subtract(goodsCost), userInfo);
                        setBalancePayCostAndUpdateOrder(goodsCost, orderInfo, payWay); // 推拿金额
                    }
                    type = 102;
                }
            }
        }

        System.out.println("type: " + type);

        return orderInfoMapper.updateByPrimaryKeyPayFlag(payWay, payWays, orderId);
    }

    @Override
    public Integer updateAccountUserInfoByPayFlag(Integer payWay, Integer orderId) {
        AccountUserInfo accountUserInfo = accountUserInfoMapper.selectByPrimaryKey(orderId);
        if (payWay == accountUserInfo.getPayWay()) {
            return -1; // 支付方式未变化
        }

        if (payWay == 7) {
            return -2; // 代付无法修改支付方式
        }

        if (payWay == 0) {
            return -3; // 卡项订单不能用余额支付
        }

        return accountUserInfoMapper.updateAccountUserInfoByPayFlag(payWay, orderId);
    }

    private void setUserAccountAndUpdateUser(BigDecimal setUserAccount, TUserInfo userInfo) {
        userInfo.setUserAccount(setUserAccount);
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    private void setBalancePayCostAndUpdateOrder(BigDecimal setBalancePayCost, TOrderInfo orderInfo, Integer payWay) {
        orderInfo.setBalancePayCost(setBalancePayCost);
        orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

        // 更新流程表的支付方式
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderInfo.getOrderId());
        List<AccountUserInfo> accountUserInfos = accountUserInfoMapper.selectByMap(params);
        for (AccountUserInfo accountUserInfo : accountUserInfos) {
            accountUserInfo.setPayWay(payWay);
            accountUserInfo.setBalancePayCost(setBalancePayCost);
            accountUserInfoMapper.updateByPrimaryKeySelective(accountUserInfo);
        }
    }

    private void updateAccountUserInfo(Integer orderId, Integer payWay, BigDecimal balancePayCost) {
        // 更新流程表的支付方式
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        List<AccountUserInfo> accountUserInfos = accountUserInfoMapper.selectByMap(params);
        for (AccountUserInfo accountUserInfo : accountUserInfos) {
            accountUserInfo.setPayWay(payWay);
            accountUserInfo.setBalancePayCost(balancePayCost);
            accountUserInfoMapper.updateByPrimaryKeySelective(accountUserInfo);
        }
    }

    private int optionUpdate(BigDecimal orderTotalCost, BigDecimal balancePayCost, BigDecimal userBeforeAccount, TOrderInfo orderInfo, TUserInfo userInfo, Integer payWay) {
        BigDecimal otherPayCost = orderTotalCost.subtract(balancePayCost); // 推拿金额
        BigDecimal detaAccount = balancePayCost.subtract(otherPayCost); // 余额变化

        if (userBeforeAccount.add(detaAccount).doubleValue() < 0) {
            return -4; // 余额不足
        } else {
            setUserAccountAndUpdateUser(userBeforeAccount.add(detaAccount), userInfo);
            setBalancePayCostAndUpdateOrder(otherPayCost, orderInfo, payWay); // 推拿金额
        }
        return 1;
    }

    private BigDecimal selectServiceCost(Integer orderId) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        List<TOrderServiceDetail> serviceDetails = orderServiceDetailMapper.selectByMap(params);
        BigDecimal serviceCost = new BigDecimal(0);
        for (TOrderServiceDetail detail : serviceDetails) {
            serviceCost = serviceCost.add(detail.getServiceCost());
        }
        return serviceCost;
    }

    public static void remove(List<String> list, String target) {
        for (int i = list.size() - 1; i >= 0; i--) {
            String item = list.get(i);
            if (target.equals(item)) {
                list.remove(item);
            }
        }
    }

}
